package com.ruoyi.system.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysQuestion;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.diagnosis.ScoreUtil;
import com.ruoyi.system.domain.SysDiagnosisDetail;
import com.ruoyi.system.domain.SysDiagnosisTask;
import com.ruoyi.system.mapper.SysDiagnosisDetailMapper;
import com.ruoyi.system.service.ISysDiagnosisTaskService;
import com.ruoyi.system.service.ISysQuestionRecordService;
import com.ruoyi.system.service.ISysQuestionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysNaire;
import com.ruoyi.system.service.ISysNaireService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 问卷数据Controller
 *
 * @author ruoyi
 * @date 2022-05-20
 */
@Api(tags = "问卷数据")
@RestController
@RequestMapping("/system/naire")
public class SysNaireController extends BaseController {
    @Autowired
    private ISysQuestionService sysQuestionService;

    @Autowired
    private ISysNaireService sysNaireService;

    @Autowired
    private ISysDiagnosisTaskService sysDiagnosisTaskService;

    @Autowired
    private SysDiagnosisDetailMapper sysDiagnosisDetailMapper;

    @Autowired
    private ISysQuestionRecordService sysQuestionRecordService;


    /**
     * 查询问卷数据列表
     */
    //  @PreAuthorize("@ss.hasPermi('system:naire:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysNaire sysNaire) {
        startPage();
        List<SysNaire> list = sysNaireService.selectSysNaireList(sysNaire);
        return getDataTable(list);
    }
    /**
     * 查询问卷数据列表
     */
    // @PreAuthorize("@ss.hasPermi('system:naire:list')")
    @GetMapping("/list2")
    public AjaxResult list2(SysNaire sysNaire) {

        List<SysNaire> list = sysNaireService.selectSysNaireList(sysNaire);
        return AjaxResult.success(list);
    }
    /**
     * 查询公司问卷数据列表
     */
    //    @PreAuthorize("@ss.hasPermi('system:naire:list')")
    @GetMapping("/listforcompany/{companyId}")
    public AjaxResult listforcompany(@PathVariable("companyId") Long companyId) {
       List< SysDiagnosisTask> tasks = sysDiagnosisTaskService.selectSysDiagnosisTaskByCompanyId(companyId);
        if (tasks == null)
            return AjaxResult.success("尚未开始诊断");
            List<SysNaire> list = new ArrayList<>();
            HashMap<Long,String> status = new HashMap<>();

            for (SysDiagnosisTask task:tasks){
                SysNaire naire = sysNaireService.selectSysNaireByNaireId(task.getNaireId());
                list.add(naire);
                status.put(naire.getNaireId(),task.getStatus());
            }
        AjaxResult result=AjaxResult.success();
            result.put("nairelist",list);
            result.put("status",status);
        return result;
    }

    /**
     * 获取问卷数据详细信息
     */
    // @PreAuthorize("@ss.hasPermi('system:naire:query')")
    @GetMapping(value = "/listquestions")
    public AjaxResult getNaireQuestions(SysQuestion query) {
        if (query.getNaireId() == null) {
            List< SysDiagnosisTask> tasks= sysDiagnosisTaskService.selectSysDiagnosisTaskByCompanyId(query.getCompanyId());
            if (tasks == null)
                return AjaxResult.success("尚未开始诊断");
            if (tasks.size()>0) {
              query.setNaireId(tasks.get(0).getNaireId());            }
        }

        SysNaire naire = sysNaireService.selectSysNaireByNaireId(query.getNaireId());
        List<String> quesetionIds = Arrays.asList(naire.getQuestions().substring(1, naire.getQuestions().length() - 1).split(","));

        List<SysQuestion> questions = sysQuestionService.selectSysQuestionListWithRecords(query);
        List<SysQuestion> result = new ArrayList<>();
        for (SysQuestion question : questions) {
            if (quesetionIds.contains(question.getQuestionId() + ""))
                result.add(result.size(), question);
        }

        return AjaxResult.success(result);
    }

    /**
     * 查询问题数据列表
     */
    @GetMapping(value = "/listquestions2")
    public AjaxResult getNaireQuestions2(SysQuestion query) {
        if (query.getNaireId() == null) {
            List< SysDiagnosisTask> tasks= sysDiagnosisTaskService.selectSysDiagnosisTaskByCompanyId(query.getCompanyId());
            if (tasks == null)
                return AjaxResult.success("尚未开始诊断");
            if (tasks.size()>0) {
                query.setNaireId(tasks.get(0).getNaireId());
            }
        }


        SysNaire naire = sysNaireService.selectSysNaireByNaireId(query.getNaireId());
        List<String> quesetionIds = Arrays.asList(naire.getQuestions().substring(1, naire.getQuestions().length() - 1).split(","));

        SysDiagnosisDetail dquery = new SysDiagnosisDetail();
        dquery.setCompanyId(query.getCompanyId());
        dquery.setNaireId(query.getNaireId());
        List<SysDiagnosisDetail> dds = sysDiagnosisDetailMapper.selectSysDiagnosisDetailList(dquery);

        HashMap<Long, Double> scores = new HashMap<>();

        if (dds != null) {
            for (SysDiagnosisDetail d : dds) {
                scores.put(d.getQuestionId(), d.getScore());
            }
        }
        List<SysQuestion> questions = sysQuestionService.selectSysQuestionListWithRecords(query);
        List<SysQuestion> result = new ArrayList<>();
        for (SysQuestion question : questions) {
            if (quesetionIds.contains(question.getQuestionId() + "")) {
                if (scores.containsKey(question.getQuestionId()))
                    question.setGrade(scores.get(question.getQuestionId()));
                else
                    question.setGrade(ScoreUtil.getGrade(question));
                result.add(result.size(), question);
            }

        }

        return AjaxResult.success(result);
    }

    @GetMapping(value = "/startdiagnosis4gleader")
    public AjaxResult startDiagnosis4GLeader(SysQuestion query) {
        if (query.getNaireId() == null) {
            List< SysDiagnosisTask> tasks= sysDiagnosisTaskService.selectSysDiagnosisTaskByCompanyId(query.getCompanyId());
            if (tasks == null)
                return AjaxResult.success("尚未开始诊断");
            if (tasks.size()>0) {
                query.setNaireId(tasks.get(0).getNaireId());
            }
        }

        sysQuestionRecordService.mergeRecordsForGroupLeader(query.getCompanyId(),query.getNaireId());

        SysNaire naire = sysNaireService.selectSysNaireByNaireId(query.getNaireId());
        List<String> quesetionIds = Arrays.asList(naire.getQuestions().substring(1, naire.getQuestions().length() - 1).split(","));

        SysDiagnosisDetail dquery = new SysDiagnosisDetail();
        dquery.setCompanyId(query.getCompanyId());
        dquery.setNaireId(query.getNaireId());

        List<SysDiagnosisDetail> dds = sysDiagnosisDetailMapper.selectSysDiagnosisDetailList(dquery);

        HashMap<Long, Double> scores = new HashMap<>();

        if (dds != null) {
            for (SysDiagnosisDetail d : dds) {
                scores.put(d.getQuestionId(), d.getScore());
            }
        }
        List<SysQuestion> questions = sysQuestionService.selectSysQuestionListWithRecords(query);
        List<SysQuestion> result = new ArrayList<>();
        for (SysQuestion question : questions) {
            if (quesetionIds.contains(question.getQuestionId() + "")) {
                if (scores.containsKey(question.getQuestionId()))
                    question.setGrade(scores.get(question.getQuestionId()));
                else
                    question.setGrade(ScoreUtil.getGrade(question));
                result.add(result.size(), question);
            }

        }

        return AjaxResult.success(result);
    }

    /**
     * 导出问卷数据列表
     */
    @PreAuthorize("@ss.hasPermi('system:naire:export')")
    @Log(title = "问卷数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysNaire sysNaire) {
        List<SysNaire> list = sysNaireService.selectSysNaireList(sysNaire);
        ExcelUtil<SysNaire> util = new ExcelUtil<SysNaire>(SysNaire.class);
        util.exportExcel(response, list, "问卷数据数据");
    }

    /**
     * 获取问卷数据详细信息
     */
    //  @PreAuthorize("@ss.hasPermi('system:naire:query')")
    @GetMapping(value = "/{naireId}")
    public AjaxResult getInfo(@PathVariable("naireId") Long naireId) {
        return AjaxResult.success(sysNaireService.selectSysNaireByNaireId(naireId));
    }


    /**
     * 新增问卷数据
     */
    //  @PreAuthorize("@ss.hasPermi('system:naire:add')")
    @Log(title = "问卷数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysNaire sysNaire) {
        sysNaire.setCreateBy(getUsername());
        return toAjax(sysNaireService.insertSysNaire(sysNaire));
    }

    /**
     * 修改问卷数据
     */
    //@PreAuthorize("@ss.hasPermi('system:naire:edit')")
    @Log(title = "问卷数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysNaire sysNaire) {
        sysNaire.setUpdateBy(getUsername());
        return toAjax(sysNaireService.updateSysNaire(sysNaire));
    }

    /**
     * 删除问卷数据
     */
    // @PreAuthorize("@ss.hasPermi('system:naire:remove')")
    @Log(title = "问卷数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{naireIds}")
    public AjaxResult remove(@PathVariable Long[] naireIds) {
        return toAjax(sysNaireService.deleteSysNaireByNaireIds(naireIds));
    }



    /**
     * 获取问卷数据详细信息
     */
    @ApiOperation(value = "获取问卷数据详细信息")
    // @PreAuthorize("@ss.hasPermi('system:naire:query')")
    @GetMapping(value = "/list/questions")
    public AjaxResult getNaireListQuestions(SysQuestion query) {

        SysNaire naire = sysNaireService.selectSysNaireByNaireId(query.getNaireId());
        List<String> quesetionIds = Arrays.asList(naire.getQuestions().substring(1, naire.getQuestions().length() - 1).split(","));

        List<SysQuestion> questions = sysQuestionService.selectSysQuestionListWithRecords(query);
        List<SysQuestion> result = new ArrayList<>();
        for (SysQuestion question : questions) {
            if (quesetionIds.contains(question.getQuestionId() + ""))
                result.add(result.size(), question);
        }

        return AjaxResult.success(result);
    }


    /**
     * 查询问题数据列表
     */
   // @ApiOperation(value = "获取问卷数据详细信息（带结果）")
    @GetMapping(value = "/list/questions2")
    public AjaxResult getNaireListQuestions2(SysQuestion query) {


        SysNaire naire = sysNaireService.selectSysNaireByNaireId(query.getNaireId());
        List<String> quesetionIds = Arrays.asList(naire.getQuestions().substring(1, naire.getQuestions().length() - 1).split(","));

        List<SysQuestion> questions = sysQuestionService.selectSysQuestionListWithRecords(query);
        List<SysQuestion> result = new ArrayList<>();
        for (SysQuestion question : questions) {
            if (quesetionIds.contains(question.getQuestionId() + "")) {
                question.setGrade(ScoreUtil.getGrade(question));
                result.add(result.size(), question);
            }

        }

        return AjaxResult.success(result);
    }
}
